package com.lmx.persistence.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.PropertiesFileUtil;
import com.lmx.repoDomain.tmodel.Bed;
import com.lmx.repoDomain.tmodel.Camera;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.HbeaconWarning;
import com.lmx.repoDomain.tmodel.LsMessage;
import com.lmx.repoDomain.tmodel.Message;
import com.lmx.repoDomain.tmodel.PersonLocation;
import com.lmx.repoDomain.tmodel.Tenant;
import com.lmx.repoDomain.tmodel.UserSession;
import com.lmx.repoDomain.tmodel.Wechat;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

/**
 * 消息处理类
 */
@Service
public class MessageService {
	private Log logger = LogFactory.getLog(this.getClass());

	private Properties properties = PropertiesFileUtil.getApplicationProperties();

	@PersistenceContext
	private EntityManager em;

	@Autowired
	private GenericService dslJpaService;

	@Autowired
	private CommonService commonService;

	@Autowired
	private UserService userService;

	@Autowired
	private WorkPlaceService workPlaceService;

	@Autowired
	private CameraService cameraService;

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	protected JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	/**
	 * 呼叫发送消息
	 */
	public void sendMessage(Message message, Long userId) {
		// 获取对应 WebSocketSession
		String uid = userId.toString();
		logger.debug("test websocket start sendMsg uid " + uid + " sessionData "
				+ ActionContextHolder.getUidSocketSessionHolder().get(uid));
		if (ActionContextHolder.getUidSocketSessionHolder().get(uid) == null
				|| ActionContextHolder.getUidSocketSessionHolder().get(uid).size() == 0) {
			logger.debug("test websocket签到：未能获取有效token   uid：" + uid);
			return;
		}
		List<WebSocketSession> sessions = new ArrayList<>();
		try {
			sessions = ActionContextHolder.getUidSocketSessionHolder().get(uid);
		} catch (Exception e1) {
			logger.debug("test websocket list sessionsl：" + e1);
		}
		for (Iterator<WebSocketSession> it = sessions.iterator(); it.hasNext();) {
			WebSocketSession session = it.next();
			logger.debug("test websocket start sendMsg2 uid " + uid + "sessionData " + session);
			if (session == null) {
				logger.debug("test websocket签到：未能获取WebSocketSession   uid：" + uid);
				return;
			}
			// 配置json转换过滤规则
			JsonConfig config = new JsonConfig();
			config.setJsonPropertyFilter(new PropertyFilter() {
				@Override
				public boolean apply(Object source, String name, Object value) {
					if (name.equals("toUser") || name.equals("fromUser") || name.equals("userList")
							|| name.equals("tenant")) {
						return true;
					} else {
						return false;
					}
				}
			});
			logger.debug("test websocket 1：");
			JSONObject jsonObject = JSONObject.fromObject(message, config);
			logger.debug("test websocket 2：");
			JSONObject fromUserJson = new JSONObject();
			logger.debug("test websocket 3：");
			// if (message.getFromUser() != null) {
			// logger.debug("test websocket 4：" );
			// fromUserJson
			// .put("id", message.getFromUser().getId().toString());
			// fromUserJson.put("name", message.getFromUser().getName()
			// .toString());
			// }
			// logger.debug("test websocket 4："+fromUserJson.toString() );
			// jsonObject.put("fromUser", fromUserJson.toString());
			// logger.debug("test websocket 5："+fromUserJson.toString() );
			// jsonObject.put("toUser",JSONObject.fromObject(message.getToUser().toString()));
			String jsonContent = jsonObject.toString();
			logger.debug("test websocket 发送消息：" + jsonContent);
			try {
				session.sendMessage(new TextMessage(jsonContent));
			} catch (Exception e) {
				logger.debug("test websocket发送信息失败：" + e.toString());
			}
		}
	}

	/**
	 * 视频发送消息
	 */
	public void sendMessage(Message message, String token) {
		// 获取token对应 WebSocketSession
		if (token == null || ActionContextHolder.getEvaHolder().get(token) == null
				|| ActionContextHolder.getEvaHolder().get(token).getWebSocketSession() == null) {
			logger.debug("livetest 未能获取有效WebSocketSession  token:" + token);
			return;
		}
		WebSocketSession session = ActionContextHolder.getEvaHolder().get(token).getWebSocketSession();
		// 配置json转换过滤规则
		JsonConfig config = new JsonConfig();
		config.setJsonPropertyFilter(new PropertyFilter() {
			@Override
			public boolean apply(Object source, String name, Object value) {
				if (name.equals("toUser") || name.equals("fromUser") || name.equals("userList")
						|| name.equals("tenant")) {
					return true;
				} else {
					return false;
				}
			}
		});
		JSONObject jsonObject = JSONObject.fromObject(message, config);
		String jsonContent = jsonObject.toString();
		logger.debug("livetest webSocket 发送消息：" + jsonContent);
		try {
			session.sendMessage(new TextMessage(jsonContent));
		} catch (Exception e) {
			logger.debug("webSocket发送信息失败：" + e.toString());
		}
	}

	/**
	 * 视频发送消息 通过设备code
	 */
	public void sendMessageByDeviceCode(Message message, String deviceCode) {
		List<String>  tokens = ActionContextHolder.getCameraTokenHolder().get(deviceCode);
		if (tokens == null || tokens.size() == 0) {
			return;
		}
		for(String token:tokens){
			// 获取token对应 WebSocketSession
			if (token == null || ActionContextHolder.getEvaHolder().get(token) == null
					|| ActionContextHolder.getEvaHolder().get(token).getWebSocketSession() == null) {
				logger.debug("livetest 未能获取有效WebSocketSession  token:" + token);
				return;
			}
			WebSocketSession session = ActionContextHolder.getEvaHolder().get(token).getWebSocketSession();
			// 配置json转换过滤规则
			JsonConfig config = new JsonConfig();
			config.setJsonPropertyFilter(new PropertyFilter() {
				@Override
				public boolean apply(Object source, String name, Object value) {
					if (name.equals("toUser") || name.equals("fromUser") || name.equals("userList")
							|| name.equals("tenant")) {
						return true;
					} else {
						return false;
					}
				}
			});
			JSONObject jsonObject = JSONObject.fromObject(message, config);
			String jsonContent = jsonObject.toString();
			logger.debug("livetest webSocket 发送消息：" + jsonContent);
			try {
				session.sendMessage(new TextMessage(jsonContent));
			} catch (Exception e) {
				logger.debug("webSocket发送信息失败：" + e.toString());
			}
		}
	}
	
	/**
	 * 发送消息
	 */
	public void sendMessage(Message message) {
		// 获取对应 WebSocketSession
		String uid = message.getToUser().getId().toString();
		if (ActionContextHolder.getUidSocketSessionHolder().get(uid) == null
				|| ActionContextHolder.getUidSocketSessionHolder().get(uid).size() == 0) {
			logger.debug("签到：未能获取有效token   uid：" + uid);
			return;
		}
		for (WebSocketSession session : ActionContextHolder.getUidSocketSessionHolder().get(uid)) {
			if (session == null) {
				logger.debug("签到：未能获取WebSocketSession   uid：" + uid);
				return;
			}
			// 配置json转换过滤规则
			JsonConfig config = new JsonConfig();
			config.setJsonPropertyFilter(new PropertyFilter() {
				@Override
				public boolean apply(Object source, String name, Object value) {
					if (name.equals("toUser") || name.equals("fromUser") || name.equals("userList")
							|| name.equals("tenant")) {
						return true;
					} else {
						return false;
					}
				}
			});
			JSONObject jsonObject = JSONObject.fromObject(message, config);
			JSONObject fromUserJson = new JSONObject();
			if (message.getFromUser() != null) {
				fromUserJson.put("id", message.getFromUser().getId().toString());
				fromUserJson.put("name", message.getFromUser().getName().toString());
			}
			jsonObject.put("fromUser", fromUserJson.toString());
			// jsonObject.put("toUser",JSONObject.fromObject(message.getToUser().toString()));
			String jsonContent = jsonObject.toString();
			logger.debug("webSocket 发送消息：" + jsonContent);
			try {
				session.sendMessage(new TextMessage(jsonContent));
			} catch (Exception e) {
				logger.debug("webSocket发送信息失败：" + e.toString());
			}
		}
	}

	/**
	 * 向本地server发送消息
	 * 
	 * @param String
	 *            tenantCode 对应的本地机构编码
	 * @param LsMessage
	 *            message 消息体
	 * @throws IOException
	 */
	public Integer sendMessageTols(String tenantCode, LsMessage message) throws IOException {
		WebSocketSession session = ActionContextHolder.getLocalSocketSessionHolder().get(tenantCode);
		if (session == null || !session.isOpen()) {
			return 0;
		}
		String content = JSONObject.fromObject(message).toString();
		logger.debug("livetest sendMessageTols " + content);
		try {
			session.sendMessage(new TextMessage(content));
		} catch (Exception e) {
			logger.debug("livetest webSocket发送信息失败：" + e.toString());
			return 0;
		}
		logger.debug("livetest sendMessageTols success " + content);
		return 1;
	}

	/**
	 * 保存本地服务器的socket session
	 */
	public void saveLocalServerSession(String tenantCode, WebSocketSession session) {
		if (ActionContextHolder.getLocalSocketSessionHolder().get(tenantCode) != null) {
			try {
				ActionContextHolder.getLocalSocketSessionHolder().get(tenantCode).close();
			} catch (IOException e) {
				logger.debug("saveLocalServerSession close session " + e);
			}
		}
		// 放到全局存储中
		ActionContextHolder.getLocalSocketSessionHolder().put(tenantCode, session);
	}

	/**
	 * 保存WebSocketSession
	 */
	public void saveSession(String message, WebSocketSession session) {
		logger.debug("test websocket savesession 0 message:" + message);
		int start = message.indexOf("{");
		int end = message.indexOf("}");
		String jsonStr = "";
		if (start > -1 && end > -1) {
			jsonStr = StringUtils.substring(message, start, end + 1);
			JSONObject jsonObject = JSONObject.fromObject(jsonStr);
			String code = jsonObject.get("code").toString(); // 获取协议号
			logger.debug("test websocket savesession code ：" + code);
			if (StringUtils.isBlank(code) || !"01".equals(code)) {
				logger.debug("test websocket savesession Session未保存");
				return;
			}
			logger.debug("test websocket savesession messageJson:" + jsonObject.toString());
			// token信息
			String token = (String) jsonObject.get("token");
			// token 对应 uid
			if (ActionContextHolder.getEvaHolder().get(token) == null) {
				logger.debug("test websocket savesession not found token:" + token);
				return;
			}
			// token与 WebSocketSession建立关联
			ActionContextHolder.getEvaHolder().get(token).setWebSocketSession(session);
			ActionContextHolder.getSocketTokenHolder().put(session.hashCode() + "", token);
			logger.debug("test websocket savesession 1 uid:" + ActionContextHolder.getEvaHolder().get(token).getId());
			// uid与多个WebSocketSession建立关联
			if (ActionContextHolder.getEvaHolder().get(token).getId() != null) {
				if (ActionContextHolder.getUidSocketSessionHolder()
						.get(ActionContextHolder.getEvaHolder().get(token).getId().toString()) == null) {
					List<WebSocketSession> sessions = new ArrayList<>();
					sessions.add(session);
					logger.debug("test websocket savesessionList  "
							+ ActionContextHolder.getEvaHolder().get(token).getId().toString() + "token " + token
							+ " socketsession " + session);
					ActionContextHolder.getUidSocketSessionHolder()
							.put(ActionContextHolder.getEvaHolder().get(token).getId().toString(), sessions);
				} else {
					logger.debug("test websocket savesessionList2  "
							+ ActionContextHolder.getEvaHolder().get(token).getId().toString() + "token " + token
							+ " socketsession " + session);
					if (!ActionContextHolder.getUidSocketSessionHolder()
							.get(ActionContextHolder.getEvaHolder().get(token).getId().toString()).contains(session)) {
						ActionContextHolder.getUidSocketSessionHolder()
								.get(ActionContextHolder.getEvaHolder().get(token).getId().toString()).add(session);
					}
				}
			}
			logger.debug("test websocket savesession 保存webSocketSession,token=" + token + ":::::userId :　"
					+ ActionContextHolder.getEvaHolder().get(token).getId());
		}
	}

	/**
	 * 发送微信绑定提醒
	 */
	public void wechatBindRemind(Wechat wechat) {
		logger.debug("进入微信绑定提醒");

		String code = "1205"; // 协议号
		String business = ""; // 业务编码
		Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.WECHATBIND.ordinal(); // 提醒详细类型
		User user = wechat.getUser();
		String failReason = "";// 失败原因

		if (wechat.getBindStatus() == ICommonConstants.BINDSTATUS.TRUE.ordinal()) {
			business = "bindWechatSucc";
			logger.debug("微信绑定成功");
		} else if (wechat.getBindStatus() == ICommonConstants.BINDSTATUS.FALSE.ordinal()) {
			business = "rechargeFail";
			failReason = "微信接口调用失败";
			logger.debug("微信绑定失败");
		}

		Message message = new Message();
		message.setFromUser(commonService.getSystemUser());// 系统
		message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
		message.setDetailType(detailType);
		message.setToUser(user);
		message.setCode(code);
		message.setBusiness(business);
		message.setHasRead((short) ICommonConstants.HASREAD.FALSE.ordinal());
		// 设置content debugTest
		Map<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("userId", user.getId().toString());
		msgMap.put("businessTypeName", business);
		msgMap.put("failReason", failReason);
		message.setContent(CommonUtil.mapToJsonString(msgMap));
		dslJpaService.setEntityClass(Message.class);
		message = (Message) dslJpaService.create(message);
		sendMessage(message);
		logger.debug("开始微信绑定提醒");

	}

	/**
	 * 获取
	 */
	public List getLatestMessage() {
		Map<Short, Message> messageMap = new HashMap<>();
		List dataListTemp = new ArrayList<>();
		List dataList = new ArrayList<>();
		// 获取时间最近的消息
		StringBuilder sql = new StringBuilder("select a.* from tnb_message a "
				+ "inner join (select detail_type,max(create_time) create_time from tnb_message group by detail_type)b "
				+ "on a.detail_type=b.detail_type and a.create_time=b.create_time where a.del_status!=1 order by a.detail_type");

		dataListTemp = getJdbcTemplate().queryForList(sql.toString());
		Iterator it = dataListTemp.iterator();
		while (it.hasNext()) {
			Map rece = (Map) it.next();
			System.out.println(rece.get("tenant_id") + "---" + rece.get("id") + "---" + rece.get("detail_type") + "---"
					+ rece.get("create_time") + "---" + rece.get("content"));
			Message temp = new Message();
			Tenant tenant = new Tenant();
			tenant.setId(Long.parseLong(rece.get("tenant_id").toString()));
			temp.setDetailType(Short.parseShort(rece.get("detail_type").toString()));
			temp.setCreateTime(Integer.parseInt(rece.get("create_time").toString()));
			temp.setContent(rece.get("content").toString());
			temp.setBusiness(rece.get("business").toString());
			temp.setId(Long.parseLong(rece.get("id").toString()));// 可能存在重复
			messageMap.put(temp.getDetailType(), temp);
			System.out.println(temp.getDetailType() + " " + messageMap.size() + " "
					+ messageMap.get(temp.getDetailType()).getContent());
		}
		// 获取每类消息未读数目 将相应数目set消息 num
		StringBuilder sql2 = new StringBuilder(
				"select detail_type type,count(*) num from tnb_message where del_status!=1 and has_read=0 group by detail_type");
		dataListTemp.clear();
		dataListTemp = getJdbcTemplate().queryForList(sql2.toString());
		it = dataListTemp.iterator();
		while (it.hasNext()) {
			Map rece = (Map) it.next();
			System.out.println(rece.get("tenant_id") + "---" + rece.get("id") + "---" + rece.get("detail_type") + "---"
					+ rece.get("create_time") + "---" + rece.get("content"));
			if (messageMap.containsKey(Short.parseShort(rece.get("type").toString()))) {
				messageMap.get(Short.parseShort(rece.get("type").toString()))
						.setNum(Integer.parseInt(rece.get("num").toString()));
			}
		}
		it = messageMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			Message val = (Message) entry.getValue();
			dataList.add(val);
		}
		return dataList;
	}

	/**
	 * 发送预警提醒
	 */
	public void warningRemind(HbeaconWarning warning, String type) {
		logger.debug("进入预警提醒方法");
		Message message = new Message();
		Customer customer = warning.getCaller();
		List<User> users = userService.getAllUserList(customer.getTenant());// 本机构所有人
		if (users != null && users.size() > 0) {
			Short detailType = null;
			if ("".equals(type) || type == null) {
				detailType = (short) ICommonConstants.REMINDDETAILTYPE.HBEACONCALL.ordinal(); // 按键提醒详细类型11
				message.setBusiness("buttonCalling");
			}
			if ("warn".equals(type)) {// 床垫 心率骤降
				detailType = (short) ICommonConstants.REMINDDETAILTYPE.HEARTRATECALL.ordinal(); // 提醒详细类型10
				if (warning.getReason() != null && warning.getReason().contains("心率")) {
					message.setBusiness("xinlv");
				}
				if (warning.getReason() != null && warning.getReason().contains("呼吸")) {
					message.setBusiness("huxi");
				}
			}
			if ("mattressStatus".equals(type)) {// 离床
				detailType = (short) ICommonConstants.REMINDDETAILTYPE.LEAVEBEDCALL.ordinal(); // 提醒详细类型9
				if (warning.getReason() != null && warning.getReason().contains("离")) {
					message.setBusiness("lichuang");
				}
				if (warning.getReason() != null && warning.getReason().contains("回")) {
					message.setBusiness("huichuang");
				}
			}
			Bed bed = workPlaceService.getBed(customer.getBed());
			message.setType(new Integer(CommonConstants.MESSAGE.MESSAGETYPE_NOTICE.label()).shortValue());
			message.setCode(CommonConstants.MESSAGE.MESSAGECODE_CALLINGNOTICE.label());
			message.setCreateTime(CommonUtil.getCurrTimes());
			message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
			message.setDetailType(detailType);
			message.setTenant(customer.getTenant());
			message.setCreateTime(CommonUtil.getCurrTimes());
			// 设置content debugTest
			Map<String, String> msgMap = new HashMap<String, String>();
			// message.setToUser(user);
			// 设置消息内容
			msgMap.put("createTime", String.valueOf(CommonUtil.getCurrTimes()));
			if (customer != null) {
				msgMap.put("customerId", customer.getId().toString());
				msgMap.put("customerName", customer.getName());
			}
			msgMap.put("bedId", warning.getBed().getId().toString());
			msgMap.put("location", bed.getRoom().getFloor().getBuilding().getName() + "-"
					+ bed.getRoom().getFloor().getName() + "-" + bed.getRoom().getName());
			// msgMap.put("bedName", bed.getName());
			msgMap.put("content", warning.getReason());
			message.setContent(CommonUtil.mapToJsonString(msgMap));
			// 使用类型作为通知的业务类型
			message.setHasRead(new Integer(0).shortValue());
			// 取得需要发送的用户--发送给所有本机构的人员
			message.setUserList(users);
			dslJpaService.setEntityClass(Message.class);
			message = (Message) dslJpaService.create(message);
			ActionContextHolder.getMessageQueue().addWarningMsg(message);
		}
		// sendMessage(message);
		logger.debug("开始预警提醒");
	}

	/**
	 * 发送位置提醒
	 */
	public void locationRemind(PersonLocation location) {
		logger.debug("进入位置提醒方法");
		Message message = new Message();
		Customer customer = location.getCustomer();
		List<User> users = userService.getAllUserList(customer.getTenant());// 本机构所有人
		if (users != null && users.size() > 0) {
			Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.LOCATIONINFO.ordinal(); // 提醒详细类型
			message.setType(new Integer(CommonConstants.MESSAGE.MESSAGETYPE_NOTICE.label()).shortValue());
			message.setCode(CommonConstants.MESSAGE.MESSAGECODE_LOCATIONNOTICE.label());
			message.setCreateTime(CommonUtil.getCurrTimes());
			message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
			message.setDetailType(detailType);
			message.setTenant(customer.getTenant());
			message.setCreateTime(CommonUtil.getCurrTimes());
			// 设置content debugTest
			Map<String, String> msgMap = new HashMap<String, String>();
			// message.setToUser(user);
			// 设置消息内容
			msgMap.put("createTime", String.valueOf(CommonUtil.getCurrTimes()));
			if (customer != null) {
				msgMap.put("customerId", customer.getId().toString());
				msgMap.put("customerName", customer.getName());
			}
			msgMap.put("roomId", location.getRoom().getId().toString());
			msgMap.put("type", "1");
			msgMap.put("location", location.getRoom().getFloor().getBuilding().getName() + "-"
					+ location.getRoom().getFloor().getName() + "-" + location.getRoom().getName());
			// msgMap.put("bedName", bed.getName());
			msgMap.put("content", "位置提醒");
			message.setContent(CommonUtil.mapToJsonString(msgMap));
			// 使用类型作为通知的业务类型
			message.setBusiness("hbeaconlocation");
			message.setHasRead(new Integer(0).shortValue());
			// 取得需要发送的用户--发送给所有本机构的人员
			message.setUserList(users);
			dslJpaService.setEntityClass(Message.class);
			message = (Message) dslJpaService.create(message);
			ActionContextHolder.getMessageQueue().addWarningMsg(message);
		}
		// sendMessage(message);
		logger.debug("开始位置提醒");
	}

	/**
	 * webSocket关闭之后的相关操作
	 *
	 * @author ytche
	 * @param session
	 * @date 2017年8月29日 上午11:17:03
	 */
	public void closeSession(WebSocketSession session) {
		if (session == null) {
			return;
		}
		// 当前session对应token
		String token = ActionContextHolder.getSocketTokenHolder().get(session.hashCode() + "");
		if (token != null) {
			// token正在拉流视频设备列表
			List<String> cameraList = ActionContextHolder.getTokenCameraHolder().get(token);
			// 修改设备拉流信息
			if (cameraList != null) {
				// 获取当前租户
				Tenant tenant = new Tenant();
				StringBuilder queryTenant = new StringBuilder("select c from Tenant c where c.id = ?2   ");
				List<Tenant> tenants = this.em.createQuery(queryTenant.toString())
						.setParameter(2, ActionContextHolder.getContext().getTenantId()).getResultList();
				tenant = tenants == null || tenants.size() == 0 ? null : tenants.get(0);
				if (tenant == null) {
					return;
				}
				for (String cameraCode : cameraList) {
					List tLis1t=ActionContextHolder.getCameraTokenHolder().get(cameraCode);
					// 修改设备对应的token列表信息
					if (ActionContextHolder.getCameraTokenHolder().get(cameraCode) != null) {
						ActionContextHolder.getCameraTokenHolder().get(cameraCode).remove(token);
						List tList=ActionContextHolder.getCameraTokenHolder().get(cameraCode);
						if (ActionContextHolder.getCameraTokenHolder().get(cameraCode).size() == 0) {
							ActionContextHolder.getCameraTokenHolder().remove(cameraCode);
							// 发送本地服务停止拉流
							LsMessage message = new LsMessage();
							message.setCode("3001");
							message.setDeviceCode(cameraCode);
							message.setPushType(1);
							// 已token作为businessId
							message.setBusinessId(ActionContextHolder.getContext().getToken());
							message.setCreateTime(CommonUtil.getCurrTimes());
							message.setTenantCode(tenant.getCode());
							try {
								logger.debug("livetest stop sendMessageTols " + message);
								sendMessageTols(tenant.getCode(), message);
							} catch (IOException e) {
								logger.debug("endlive error " + tenant.getCode());
							}
						}
					}

				}
			}
			// 修改token拉流设备信息清除
			ActionContextHolder.getTokenCameraHolder().remove(token);
		}
		Map<String, UserSession> evaHolder = ActionContextHolder.getEvaHolder();
		for (Entry<String, UserSession> entry : evaHolder.entrySet()) {
			if (entry.getValue() != null && entry.getValue().getWebSocketSession() != null
					&& entry.getValue().getWebSocketSession().getId().equals(session.getId())) {
				entry.getValue().setWebSocketSession(null);
			}
		}
	}

	/**
	 * 处理视频直播反馈信息  开始拉流
	 * 
	 * @author huibati
	 * @param 2017年11月22日
	 */
	public void operateLiveRes(JSONObject jo) {
		logger.debug("livetest operateLiveRes " + jo);
		String successFlag = jo.getString("success");
		String token = jo.getString("businessId");
		String deviceCode = jo.getString("deviceCode");
		String liveUrl = properties.getProperty("local.camera.liveDomainName");
		Message msg = new Message();
		msg.setCreateTime(CommonUtil.getCurrTimes());
		msg.setDelStatus((short) 0);
		msg.setType(new Integer(CommonConstants.MESSAGE.MESSAGETYPE_NOTICE.label()).shortValue());
		msg.setCode(CommonConstants.MESSAGE.MESSAGECODE_VIDEONOTICE.label());
		// 拼装内容信息
		JSONObject content = new JSONObject();
		content.put("success", successFlag);
		// success 1 成功
		if ("1".equals(successFlag)) {
			// 建立token正对几个设备进行拉流
			if (ActionContextHolder.getTokenCameraHolder().containsKey(token)) {
				if (!ActionContextHolder.getTokenCameraHolder().get(token).contains(deviceCode)) {
					ActionContextHolder.getTokenCameraHolder().get(token).add(deviceCode);
				}
			} else {
				List<String> cameraList = new ArrayList<>();
				cameraList.add(deviceCode);
				ActionContextHolder.getTokenCameraHolder().put(token, cameraList);
			}
			// 建立设备拉流列表
			if (ActionContextHolder.getCameraTokenHolder().containsKey(deviceCode)) {
				if (!ActionContextHolder.getCameraTokenHolder().get(deviceCode).contains(token)) {
					ActionContextHolder.getCameraTokenHolder().get(deviceCode).add(token);
				}
			} else {
				List<String> tokenList = new ArrayList<>();
				tokenList.add(token);
				ActionContextHolder.getCameraTokenHolder().put(deviceCode, tokenList);
			}
			Camera camera = cameraService.findByCode(deviceCode);
			// 修改设备状态
			camera.setLiveStatus(1);// 拉流已开启
			camera.setStatus(1);// 设备已连接可用
			dslJpaService.setEntityClass(Camera.class);
			dslJpaService.update(camera);
			// 通知前端设备变化todo
			//createVideoStatusMsg(camera);
			content.put("showUrl", liveUrl + "/hls" + "/" + camera.getCode() + ".m3u8");
			content.put("cameraId", camera.getId());
			msg.setContent(content.toString());
		}
		if("0".equals(successFlag)){
			// 更改token拉流设备信息
			if (ActionContextHolder.getTokenCameraHolder()!=null) {
				for(String tokenTemp:ActionContextHolder.getTokenCameraHolder().keySet()){
					if(ActionContextHolder.getTokenCameraHolder().get(tokenTemp)!=null){
						ActionContextHolder.getTokenCameraHolder().get(tokenTemp).remove(deviceCode);
					}
				}
			}
			// 建立设备拉流列表
			if (ActionContextHolder.getCameraTokenHolder().containsKey(deviceCode)) {
				ActionContextHolder.getCameraTokenHolder().put(deviceCode,new ArrayList<String>());
			}
			Camera camera = cameraService.findByCode(deviceCode);
			// 修改设备状态
			camera.setLiveStatus(0);// 拉流未开启
			camera.setStatus(1);// 设备已连接可用
			dslJpaService.setEntityClass(Camera.class);
			dslJpaService.update(camera);
		}
		logger.debug("livetest operateLiveRes end" + content);
		this.sendMessageByDeviceCode(msg, deviceCode);

	}

	/**
	 * 处理视频直播反馈信息   开始推流
	 * 
	 * @author huibati
	 * @param 2017年11月22日
	 */
	public void operateLiveStartRes(JSONObject jo) {
		logger.debug("livetest operateLiveRes " + jo);
		String successFlag = jo.getString("success");
		String token = jo.getString("businessId");
		String deviceCode = jo.getString("deviceCode");
		String liveUrl = properties.getProperty("local.camera.liveDomainName");
		// 建立token正对几个设备进行拉流
		if (ActionContextHolder.getTokenCameraHolder().containsKey(token)) {
			if (!ActionContextHolder.getTokenCameraHolder().get(token).contains(deviceCode)) {
				ActionContextHolder.getTokenCameraHolder().get(token).add(deviceCode);
			}
		} else {
			List<String> cameraList = new ArrayList<>();
			cameraList.add(deviceCode);
			ActionContextHolder.getTokenCameraHolder().put(token, cameraList);
		}
		// 建立设备拉流列表
		if (ActionContextHolder.getCameraTokenHolder().containsKey(deviceCode)) {
			if (!ActionContextHolder.getCameraTokenHolder().get(deviceCode).contains(token)) {
				ActionContextHolder.getCameraTokenHolder().get(deviceCode).add(token);
			}
		} else {
			List<String> tokenList = new ArrayList<>();
			tokenList.add(token);
			ActionContextHolder.getCameraTokenHolder().put(deviceCode, tokenList);
		}
		//修改设备状态
	}
	
	/**
	 * 处理停止视频直播反馈信息
	 * 
	 * @author huibati
	 * @param 2017年11月22日
	 */
	public void operateStopLiveRes(JSONObject jo) {
		logger.debug("livetest operateStopLiveRes " + jo);
		String successFlag = jo.getString("success");
		String token = jo.getString("businessId");
		String deviceCode = jo.getString("deviceCode");
		// 停止成功
		if ("1".equals(successFlag)) {
			// 更改token拉流设备信息
			if (ActionContextHolder.getTokenCameraHolder()!=null) {
				for(String tokenTemp:ActionContextHolder.getTokenCameraHolder().keySet()){
					if(ActionContextHolder.getTokenCameraHolder().get(tokenTemp)!=null){
						ActionContextHolder.getTokenCameraHolder().get(tokenTemp).remove(deviceCode);
					}
				}
			}
			// 更改设备拉流列表
			if (ActionContextHolder.getCameraTokenHolder().containsKey(deviceCode)) {
				ActionContextHolder.getCameraTokenHolder().put(deviceCode,new ArrayList<String>());
			}
			Camera camera = cameraService.findByCode(deviceCode);
			// 修改设备状态
			camera.setLiveStatus(0);// 拉流已关闭
			camera.setStatus(1);// 设备已连接可用
			dslJpaService.setEntityClass(Camera.class);
			dslJpaService.update(camera);
			// 通知前端设备变化todo
			// createVideoStatusMsg(camera);
		}
		// 停止失败
		if ("0".equals(successFlag)) {
             
		}
	}

	/**
	 * 通知前端视频设备变化
	 * 
	 * @author huibati
	 * @param 设备信息
	 *            2017年11月30日
	 */
	public void createVideoStatusMsg(Camera camera) {
		List<User> users = userService.getAllUserList(camera.getTenant());// 本机构所有人
		// 建立 Message提醒
		//Short detailType = (short) ICommonConstants.REMINDDETAILTYPE.VIDEOSTATUSCALL.ordinal(); // 提醒详细类型
		Message message = new Message();
		message.setType(new Integer(CommonConstants.MESSAGE.MESSAGETYPE_NOTICE.label()).shortValue());
		message.setCode(CommonConstants.MESSAGE.MESSAGECODE_VIDEOSTATUSNOTICE.label());
		message.setCreateTime(CommonUtil.getCurrTimes());
		message.setType((short) ICommonConstants.MESSAGETYPE.REMIND.ordinal());
		// message.setDetailType(detailType);
		// message.setTenant(bed.getTenant());
		// 设置content debugTest
		Map<String, String> msgMap = new HashMap<String, String>();
		// 设置消息内容
		msgMap.put("stutus", "1");// 已连接
		msgMap.put("liveStatus", camera.getLiveStatus() + "");
		msgMap.put("localStatus", "true");
		if (ActionContextHolder.getCameraTokenHolder().containsKey(camera.getCode())
				&& ActionContextHolder.getCameraTokenHolder().get(camera.getCode()) != null) {
			msgMap.put("audienceNum", ActionContextHolder.getCameraTokenHolder().get(camera.getCode()).size() + "");
		} else {
			msgMap.put("audienceNum", "0");
		}
		msgMap.put("cameraId", camera.getId().toString());
		//msgMap.put("content", CommonConstants.BUTTON_CALLING_TYPE.NORMAL_NOTE.label());
		message.setContent(CommonUtil.mapToJsonString(msgMap));
		// 使用类型作为通知的业务类型
		message.setBusiness("videoStatusInfo");
		message.setHasRead(new Integer(0).shortValue());
		// 取得需要发送的用户--发送给所有本机构的人员
		message.setUserList(users);
		ActionContextHolder.getMessageQueue().addWarningMsg(message);
	}
}
